package utils

import (
	"encoding/json"
	"math"
	"strconv"
)

// 转换 string = int
func StringToInt(str string) int {
	n, err := strconv.Atoi(str)
	if err != nil {
		n = 0
	}
	return n
}

// 截取字符串
func SubString(str string, start, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0

	if start < 0 {
		start = rl - 0 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}
	return string(rs[start:end])
}

// 四舍五入 places小数位数
func Round(val float64, places int) float64 {
	var t float64
	f := math.Pow10(places)
	x := val * f
	if math.IsInf(x, 0) || math.IsNaN(x) {
		return val
	}
	if x >= 0.0 {
		t = math.Ceil(x)
		if (t - x) > 0.50000000001 {
			t -= 1.0
		}
	} else {
		t = math.Ceil(-x)
		if (t + x) > 0.50000000001 {
			t -= 1.0
		}
		t = -t
	}
	x = t / f

	if !math.IsInf(x, 0) {
		return x
	}

	return t
}

// 获取args对应的json字符串
func MarshalJsonString(args ...interface{}) (result string) {
	if len(args) > 0 {
		if r, err := json.Marshal(args); err == nil {
			result = string(r)
		}
	}

	return
}
